/*
 * ============================================================================
 *
 *       Filename:  common.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  01/23/2018 07:03:20 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <time.h>
#include <sys/time.h>

#include "../include/common.h"

void *ss_malloc(size_t size)
{
	void *tmp = malloc(size);
	if (tmp == NULL)
		exit(EXIT_FAILURE);
	memset(tmp, 0, size);
	return tmp;
}

void *ss_realloc(void *ptr, size_t new_size)
{
	void *new = realloc(ptr, new_size);
	if (new == NULL) {
		free(ptr);
		ptr = NULL;
		exit(EXIT_FAILURE);
	}
	return new;
}

void str_to_hex(uint8_t *hexbuf, uint8_t *strbuf, int len)
{
	int i, j;
	for(i = 0, j = 0; i < len; i++) {
		if(strbuf[i] <= '9' && strbuf[i] >= '0') {
		        if(i % 2 == 1) {
		                hexbuf[j] |= (strbuf[i] - 0x30);  //字符与16进制相差0x30
		                j++;
		        } else {
		                hexbuf[j] = ((strbuf[i] - 0x30) << 4);
		        }
		} else if(strbuf[i] <= 'Z' && strbuf[i] >= 'A') {
		        if(i % 2 == 1) {
		                hexbuf[j] |= (strbuf[i] - 0x37); // 大写字母与16进制相差0x37
		                j++;
		        } else {
		                hexbuf[j] = ((strbuf[i] - 0x37) << 4);
		        }
		} else if(strbuf[i] <= 'z' && strbuf[i] >= 'a') {
		        if(i % 2 == 1) {
		                hexbuf[j] |= (strbuf[i] - 0x57); // 小写字母与16进制相差0x37
		                j++;
		        } else {
		                hexbuf[j] = ((strbuf[i] - 0x57) << 4);
		        }
		}
	}
}
